package com.iflytek.springboot_medicine.interceptor;

import com.iflytek.springboot_medicine.exception.UnauthorizedException;
import com.iflytek.springboot_medicine.util.JwtUtil;
import com.iflytek.springboot_medicine.util.RedisUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class AuthInterceptor implements HandlerInterceptor {

    private final RedisUtil redisUtil;
    private final JwtUtil jwtUtil;

    public AuthInterceptor(RedisUtil redisUtil, JwtUtil jwtUtil) {
        this.redisUtil = redisUtil;
        this.jwtUtil = jwtUtil;
    }

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) {
        // 1. 从Header获取Token
        String token = request.getHeader("Authorization");
        if (token == null || token.isEmpty()) {
            throw new UnauthorizedException("请先登录，未提供Token");
        }

        // 2. 验证Token有效性
        Claims claims;
        try {
            claims = jwtUtil.parseToken(token);
        } catch (Exception e) {
            throw new UnauthorizedException("Token无效或已过期");
        }
        String userId = claims.getSubject();

        // 3. 检查Redis中是否存在（实现主动注销功能）
        String redisToken = String.valueOf(redisUtil.get("USER_TOKEN:" + userId));
        if (redisToken == null ||!token.equals(redisToken)) {
            throw new UnauthorizedException("Token已失效");
        }

        // 4. 将用户信息存入Request属性
        request.setAttribute("CURRENT_USER_ID", userId);
        return true;
    }
}